# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.districtDao import DistrictDao

from . import app

CORS(app, supports_credentials=True)


@app.route('/insertDistrict', methods=['POST'])
def insert_districtNoToken():
    """
    添加信息
    :return:
    """
    if not request.json:
        abort(400)
    info = {
        'distName': request.json.get('distName', ''),
        'cityId': request.json.get('cityId', '')
    }

    info = DistrictDao().insertDist(info)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findDistrictById', methods=['POST'])
def find_district_by_idNoToken():
    """
    根据ID查询
    :return:
    """
    if not request.json:
        abort(400)
    distId = request.json.get('distId', '')
    info = DistrictDao().findDistById(distId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findDistrictByCondition', methods=['POST'])
def find_district_by_conditionNoToken():
    """
    条件查询
    :return:
    """
    if not request.json:
        abort(400)

    cityId = request.json.get('cityId', '')
    info = DistrictDao().findDistByCondition(cityId=cityId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/deleteDistrictByIds', methods=['POST'])
def delete_district_by_idsNoToken():
    """
    根据ID删除，ID以数组形式传递
    :return:
    """
    if not request.json:
        abort(400)
    idArray = request.json.get('idArray', [0])

    info = DistrictDao().deleteDist(idArray)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/updateDistrictById', methods=['POST'])
def update_district_by_idNoToken():
    """
    更新
    :return:
    """
    if not request.json:
        abort(400)
    try:
        distId = request.json['distId']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入修改信息的ID"}})
    oldInfo = DistrictDao().selectDist(distId)
    info = {
        'distId': request.json['distId'],
        'distName': request.json.get('distName', oldInfo[1]),
        'cityId': request.json.get('cityId', oldInfo[2])
    }

    info = DistrictDao().updateDist(info)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})
